package com.mzy.linear_struct.ks.回溯;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: mizy3
 * @Date: 2024/08/25/下午7:41
 * @Description:
 */
public class 括号生成 {

    public List<String> generateParenthesis(int n) {
        List<String> ans = new ArrayList<>();
        if (n == 0) {
            return ans;
        }
        int open = 0, close = 0;
        StringBuilder path = new StringBuilder();
        dfs(n, ans, path, open, close);

        return ans;
    }

    private void dfs(int n, List<String> ans, StringBuilder path, int open, int close) {
        // 剪枝条件
        if (open < close || open > n) {
            return;
        }
        if (path.length() == 2 * n) {
            ans.add(path.toString());
            return;
        }

        path.append("(");
        dfs(n, ans, path, open + 1, close);
        path.deleteCharAt(path.length() - 1);
        path.append(")");
        dfs(n, ans, path, open, close + 1);
        path.deleteCharAt(path.length() - 1);
    }

    public static void main(String[] args) {
        System.out.println(new 括号生成().generateParenthesis(3));
    }
}






















